package room

import (
	"bbs-go/internal/models"
	"bbs-go/internal/services"
	"encoding/json"
	"fmt"
	"time"

	"github.com/gorilla/websocket"
)

type Client struct {
	UserId   int // 用户Id
	Conn     *websocket.Conn
	Send     chan []byte
	Room     *Room
	Nickname string
	Avatar   string
}

func (c *Client) Read() {
	defer func() {
		c.Room.Leave <- c
		c.Conn.Close()
	}()

	for {
		_, message, err := c.Conn.ReadMessage()
		if err != nil {
			if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
				fmt.Printf("read error: %v\n", err)
			}
			return
		}

		var msg SendBody
		if err := json.Unmarshal(message, &msg); err != nil {
			fmt.Printf("Error decoding message: %v\n", err)
			continue
		}

		if msg.ReceiverId == 0 {
			continue
		}

		switch {
		case msg.MessageType == 1: // 好友消息
			chatFriendsMessages := models.ChatFriendsMessages{
				SenderUserId:   c.UserId,
				ReceiverUserId: msg.ReceiverId,
				Types:          msg.ContentType,
				IsRead:         false,
			}

			if msg.ContentType == 1 {
				chatFriendsMessages.Content = msg.Content
			} else if msg.ContentType == 2 {
				chatFriendsMessages.ImageUrl = msg.Content
			}
			// 添加聊天记录到数据库
			err := services.ChatFriendsMessagesService.Create(&chatFriendsMessages)
			if err != nil {
				fmt.Printf("Error creating chat friends messages: %v\n", err)
			}
			c.Room.Broadcast <- models.WsMessage{
				MessageType: msg.MessageType,
				MessageData: models.FriendMessage{
					SenderId:       c.UserId,
					SenderNickname: c.Nickname,
					SenderAvatar:   c.Avatar,
					SendTime:       time.Now().Format("2006-01-02 15:04:05"),
					ReceiverId:     msg.ReceiverId,
					ContentType:    msg.ContentType,
					Content:        msg.Content,
				},
			}
		case msg.MessageType == 2: // 群组消息
			chatGroupsMessages := models.ChatGroupsMessages{
				GroupId:    msg.ReceiverId,
				SendUserId: c.UserId,
				Types:      msg.ContentType,
				Content:    msg.Content,
			}
			// 查询群组信息
			chatGroup, _ := services.ChatGroupsService.FindByGroupId(int64(msg.ReceiverId))
			// 添加群聊天记录到数据库
			services.ChatGroupsMessagesService.Create(&chatGroupsMessages)
			c.Room.Broadcast <- models.WsMessage{
				MessageType: msg.MessageType,
				MessageData: models.GroupMessage{
					SenderId:       c.UserId,
					SenderNickname: c.Nickname,
					SenderAvatar:   c.Avatar,
					SendTime:       time.Now().Format("2006-01-02 15:04:05"),
					GroupId:        msg.ReceiverId,
					GroupName:      chatGroup.Name,
					GroupAvatar:    chatGroup.Avatar,
					ContentType:    msg.ContentType,
					Content:        msg.Content,
				},
			}
		}
	}
}

func (c *Client) Write() {
	defer func() {
		c.Conn.Close()
	}()

	for message := range c.Send {
		err := c.Conn.WriteMessage(websocket.TextMessage, message)
		if err != nil {
			return
		}
	}
}
